﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace YinLongTool.Text
{
    public static class EncodingUtil
    {
        public static string HtmlDecode(string html)
        {
            return HttpUtility.HtmlDecode(html);
        }

        public static string HtmlEncode(string html)
        {
            return HttpUtility.HtmlEncode(html);
        }

        /// <summary>
        /// Url解码
        /// </summary>
        /// <param name="str"></param>
        /// <param name="unEncodingNumAndEnglish">不编码字母数字</param>
        /// <param name="codepage"></param>
        /// <returns></returns>
        public static string UrlEncodeEx(string str, bool unEncodingNumAndEnglish = true, string codepage = "utf-8")
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            byte[] buff = System.Text.Encoding.GetEncoding(codepage).GetBytes(str);
            StringBuilder s = new StringBuilder();
            for (int ix = 0; ix < buff.Length; ix++)
            {
                string temp = buff[ix].ToString("x2").PadLeft(2, '0');
                if (unEncodingNumAndEnglish)
                {
                    if (buff[ix] > 44 && buff[ix] < 58 && buff[ix] != 47)//-.0-9
                    {
                        s.Append( Encoding.ASCII.GetString(buff, ix, 1));
                    }
                    else if (buff[ix] > 64 && buff[ix] < 91)// A-Z
                    {
                        s.Append( Encoding.ASCII.GetString(buff, ix, 1));
                    }
                    else if (buff[ix] > 96 && buff[ix] < 123)// a-z
                    {
                        s.Append( Encoding.ASCII.GetString(buff, ix, 1));
                    }
                    else
                    {
                        s.Append("%" + temp);
                    }
                }
                else
                {
                    s.Append("%" + temp);
                }
            }
            return s.ToString();
        }
        /// <summary>
        /// URL解密适用于淘宝中文编码算法
        /// </summary>
        /// <param name="url">密文</param>
        /// <returns>明文</returns>
        public static string UrlDecodeEx(string url,bool  utf8=false)
        {
            List<byte> li2 = new List<byte>();
                int len = url.Length;
                string hex = "0123456789ABCDEF";
                int index = 0;
                string result = string.Empty;
                int h, l;
                while (index+1<=len)
                {
                    if (url.Substring(index,1)!="%")
                    {   
                        li2.Add(Convert.ToByte( url.Substring(index, 1), 16));
                    }
                    else
                    {
                        index++;
                        li2.Add(Convert.ToByte(    url.Substring(index, 1).ToUpper(), 16));
                        index++;
                        li2.Add(Convert.ToByte(    url.Substring(index, 1).ToUpper(), 16));
                    }
                    index++;
                }
                result=  Encoding.Default.GetString(li2.ToArray());//bbs.msdn5.com玄机论坛出品
                if (utf8)
                {
               result=  Gb2312ToUtf8(result);
                }
               
                return result;
           

        }
        /// <summary>
        /// JS16进制解码
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string Js16HexDecode(string text)
        {
            StringBuilder stringBuilder = new StringBuilder(text);
            for (int num = stringBuilder.ToString().IndexOf("\\x"); num != -1; num = stringBuilder.ToString().IndexOf("\\x"))
            {
                string value = stringBuilder.ToString().Substring(num + 2, 2);
                int utf = Convert.ToInt32(value, 16);
                string value2 = char.ConvertFromUtf32(utf);
                stringBuilder.Remove(num, 4);
                stringBuilder.Insert(num, value2);
            }
            return stringBuilder.ToString();
        }

        #region Url
        /// <summary>
        /// Url编码
        /// </summary>
        /// <param name="text"></param>
        /// <param name="codepage"></param>
        /// <returns></returns>
        public static string UrlEncode(string text, string codepage = "utf-8")
        {
            return HttpUtility.UrlEncode(text, System.Text.Encoding.GetEncoding(codepage));
        }
        /// <summary>
        /// Url解码
        /// </summary>
        /// <param name="text"></param>
        /// <param name="codepage"></param>
        /// <returns></returns>
        public static string UrlDecode(string text, string codepage = "utf-8")
        {
            return HttpUtility.UrlDecode(text, System.Text.Encoding.GetEncoding(codepage));
        }

        /// <summary>
        /// url 编码
        /// </summary>
        /// <param name="str"></param>
        /// <param name="e">utf8 或者gbk</param>
        /// <returns></returns>
        public static string UrlEncode(string str, System.Text.Encoding e)
        {
            return System.Web.HttpUtility.UrlEncode(str, e);
        }

        /// <summary>
        /// Url 编码 默认utf8
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UrlEncode(string str)
        {
            return System.Web.HttpUtility.UrlEncode(str, System.Text.Encoding.UTF8);
        }
        /// <summary>
        /// Url 解码 默认utf8
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UrlDecode(string str)
        {
            return System.Web.HttpUtility.UrlDecode(str, System.Text.Encoding.UTF8);
        }

        /// <summary>
        /// url 解码
        /// </summary>
        /// <param name="str"></param>
        /// <param name="e"> Encoding.Utf8 或者gbk</param>
        /// <returns></returns>
        public static string UrlDecode(string str, System.Text.Encoding e)
        {
            return System.Web.HttpUtility.UrlDecode(str, e);
        }
        #endregion URL

        #region 字节集到文本

        /// <summary>
        /// UTF8 转文本
        /// </summary>
        /// <param name="bin"></param>
        /// <returns></returns>
        public static string ByteToString(byte[] bin)
        {
            return System.Text.Encoding.UTF8.GetString(bin);
        }


        /// <summary>
        ///  转文本
        /// </summary>
        /// <param name="bin"></param>
        /// <param name="e"> 编码</param>
        /// <returns></returns>
        public static string ByteToString(byte[] bin, System.Text.Encoding e)
        {
            return e.GetString(bin);
        }

        /// <summary>
        /// 文本到节集
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] StringToByte(string str)
        {

            return System.Text.Encoding.Default.GetBytes(str);

        }
        /// <summary>
        /// gb2312到utf8
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Gb2312ToUtf8(string str)
        {
            Encoding utf8;
            Encoding gb2312;
            utf8 = Encoding.GetEncoding("UTF-8");
            gb2312 = Encoding.GetEncoding("GB2312");
            byte[] gb = gb2312.GetBytes(str);
            gb = Encoding.Convert(gb2312, utf8, gb);
            return utf8.GetString(gb);
        }
        /// <summary>
        /// utf8到gb2312
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string Utf8ToGb2312(string text)
        {
            byte[] bs = Encoding.GetEncoding("UTF-8").GetBytes(text);
            bs = Encoding.Convert(Encoding.GetEncoding("UTF-8"), Encoding.GetEncoding("GB2312"), bs);
            return Encoding.GetEncoding("GB2312").GetString(bs);
        }
        /// <summary>
        /// 文本到节集
        /// </summary>
        /// <param name="str"></param>
        /// <param name="e">Encoding 编码</param>
        /// <returns></returns>
        public static byte[] StringToByte(string str, System.Text.Encoding e)
        {
            return e.GetBytes(str);
        }


        #endregion 字节集到文本


        #region UniCode码字符串
        /// <summary>
        /// 字符串转为UniCode码字符串
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string StringToUnicode(string s)
        {
            char[] charbuffers = s.ToCharArray();
            byte[] buffer;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < charbuffers.Length; i++)
            {
                buffer = System.Text.Encoding.Unicode.GetBytes(charbuffers[i].ToString());
                sb.Append(System.String.Format("\\u{0:X2}{1:X2}", buffer[1], buffer[0]));
            }
            return sb.ToString();
        }
        /// <summary>
        /// Unicode字符串转为正常字符串
        /// </summary>
        /// <param name="srcText"></param>
        /// <returns></returns>
        public static string UnicodeToString(string srcText)
        {
            string dst = "";
            string src = srcText;
            int len = srcText.Length / 6;
            for (int i = 0; i <= len - 1; i++)
            {
                string str = "";
                str = src.Substring(0, 6).Substring(2);
                src = src.Substring(6);
                byte[] bytes = new byte[2];
                bytes[1] = byte.Parse(int.Parse(str.Substring(0, 2), System.Globalization.NumberStyles.HexNumber).ToString());
                bytes[0] = byte.Parse(int.Parse(str.Substring(2, 2), System.Globalization.NumberStyles.HexNumber).ToString());
                dst += System.Text.Encoding.Unicode.GetString(bytes);
            }
            return dst;
        }


        #endregion UniCode码字符串


    }
}
